import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';

import { HttpClient } from '@angular/common/http';
import { User } from './User';

@Component({
  selector: 'app-user-management-component',
  templateUrl: './user-management-component.component.html',
  styleUrls: ['./user-management-component.component.css']
})
export class UserManagementComponentComponent implements OnInit {

  myForm:FormGroup;
  userName:FormControl;
  id:FormControl;
  password:FormControl;
  users$!: Observable<User[]>;
  baseUrl = 'http://127.0.0.1:8080/';
  currentUser!: User;
  router: any;

  constructor(private fb: FormBuilder,private httpClient: HttpClient){
    this.myForm=this.fb.group({
      'userName':[''],
      'password':[''],
      'id':['']
    });
    this.users$ = <Observable<User[]>>this.httpClient.get(this.baseUrl + 'users');
    this.userName=<FormControl>this.myForm.controls['userName'];
    this.id=<FormControl>this.myForm.controls['id'];
    this.password=<FormControl>this.myForm.controls['password'];
  }
  //页面初始化
  ngOnInit(): void {
   
  }

  search() {
    if (this.id.value) {
      this.users$ = <Observable<User[]>>this.httpClient.get(this.baseUrl + 'users/' + this.id.value);
    } else {
      this.users$ = <Observable<User[]>>this.httpClient.get(this.baseUrl + 'users');
    }
  }

  search1() {
      this.users$ = <Observable<User[]>>this.httpClient.get(this.baseUrl + 'users');
  }

  add() {
    console.log(this.myForm.value);
    this.httpClient.post(this.baseUrl + 'user', this.myForm.value).subscribe(
      (val: any) => {
        if (val.succ) {
          alert('添加成功!');
          this.search1();
        }
      }
    )
  };
  select(u: User) {
    this.currentUser = u;
    this.myForm.setValue(this.currentUser);
  }

  delete() {
    if (!this.currentUser) {
      alert('必须先选择用户！');
    }
    else {
      this.httpClient.delete(this.baseUrl + 'user/' + this.currentUser.id).subscribe(
        (val: any) => {
          if (val.succ) {
            alert('删除成功！');
            this.search1(); 
          }
        });
    }
  }

  update() {
    if (!this.currentUser) {
      alert('必须先选择用户！');
    }
    else {
      this.httpClient.put(this.baseUrl + 'user', this.myForm.value).subscribe(
        (val: any) => {
          if (val.succ) {
            alert('修改成功！');
            this.search1();
          }
        });
    }
  }

}
function refresh(students: any) {
  throw new Error('Function not implemented.');
}

